<template>
    <div class="rank-box">
        <div class="rank-header">
            <el-text size="default">
                注：当前界面只展示代码题的实时成绩，不展示非代码题的实时成绩。赛中成绩仅作参考，不作为最终成绩依据。
            </el-text>
            <div>
                <el-button class="refresh" size="default" type="primary" @click="start">刷新</el-button>
            </div>
        </div>
        <!-- :max-height="`calc(100vh - 64px - var(--container-margin)* 5 - var(--container-header-height) - var(--rank-header-height )`" -->
        <el-table class="match-rank-table" :data="tableData" style="width: 100%" :max-height="`calc(100vh - 24px)`">
            <template v-slot:empty>
                <el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
            </template>
            <el-table-column type="index" label="排名" align="center" width="80" fixed></el-table-column>
            <el-table-column prop="username" label="成员" align="center" width="150" fixed show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.xingming ? `${row.xingming} (${row.name})` : row.name }}
                </template>
            </el-table-column>
            <el-table-column prop="df" label="总分" align="center" width="" fixed sortable></el-table-column>
            <!-- 方式一:缺点修改不了字体样式 -->
            <!-- <el-table-column prop="" :label="'题目序号' + '\n' + '题目总分'" align="center" width="100">
            </el-table-column> -->
            <!-- <el-table-column v-for="(q, key) in matchQuestion" :prop="String(key)" :label="`#${key + 1}\n${q.score}`"
                class-name="el-table-column" align="center" width="">
                <template #default="{ row: { rank } }">
                    <div class="">
                        {{ rank[key].score }}
                    </div>
                </template>
            </el-table-column> -->
            <!-- <el-table-column width="30" align="center" class-name="padding0">
                <template slot="header" #header="scope">
                    <div class="match-rank-table-header-qNo">序号</div>
                    <div class="match-rank-table-header-qScore">总分</div>
                </template>
            </el-table-column> -->
            <el-table-column v-for="(item, key) in matchQuestion" :key="key" align="center" :prop="String(key)" width=""
                class-name="el-table-column" label-class-name="match-rank-table-header">
                <template #header="{ row }">
                    <el-tooltip effect="dark" :content="item.name" placement="top">
                        <div>
                            <div class="match-rank-table-header-qNo">
                                {{ `# ${key + 1}` }}
                            </div>
                            <div class="match-rank-table-header-qScore">
                                {{ `${item.score}` }}
                            </div>
                        </div>
                    </el-tooltip>
                </template>
                <!--  -->
                <el-table-column label="得分" align="center" :width="90">
                    <template #default="{ row: { rank, userquestion } }">
                        <div v-if="showScoreColumn" :class="className(rank, item, key)">
                            {{ rank[key].score }}
                        </div>
                        <div v-else> {{ rank[key].answered ? '已提交' : '未提交' }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="测试点" align="center" :width="120" show-overflow-tooltip >
                    <template #default="{ row: { rank, userquestion } }">
                        <!-- 测试点信息 点击展开详情  v-on="showDetailedScore ? { click: (e) => { e.stopPropagation(); showACDetail(userquestion) } } : {}"-->
                        <div v-if="showDetailedScore && rank[key].type === '代码'" class="AC-detail">
                            <el-tag class="question-intable-label" effect="dark"
                                :class="['bg-' + getResultMeta(userquestion, key).className, 'margin-left10']">
                                {{ getResultMeta(userquestion, key).label }}
                            </el-tag>
                            <!-- 仅在展示详细得分时才展示测试点分布 -->
                            <!-- <span v-if="showDetailedScore && Array.isArray(userquestion?.resultdataarr[key])"
                                v-for="(e, k) in acgroup(userquestion?.resultdataarr[key])" :class="[ALLTYPE[e[0]][1],]"
                                :key="'ac_' + k">
                                &nbsp; {{ e[0] }}:{{ e[1] }}
                            </span> -->
                        </div>
                        <!-- <div v-else> {{ rank[key].answered ? '已提交' : '未提交' }}</div> -->
                        <div v-else> - </div>
                    </template>
                </el-table-column>
            </el-table-column>

        </el-table>
    </div>
</template>

<script setup lang="ts">
import { countBy } from 'lodash-es';
import { pairs } from 'underscore';
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { SHOW_AC_STATUS } from '@/admin/views/data';
import { asyncgetactivity, asyncselectmatchquestion, asyncselectmatchranking } from "@/api";
import { Storekey } from "@/interface";
import Studycodemodel from "@/mysql_interface/studycodemodel";
import { ALLTYPE } from '@/util/jianchatime';
type P = {
    activity: Studycodemodel.Iactivity
}
const p = defineProps<P>()
const router = useRouter();
const store = useStore(Storekey)
const user = computed(() => {
    return store.state.user
})

const limit = ref(1000)
const offset = ref(0)
const activity = reactive<Studycodemodel.Iactivity>({});
const format = computed(() => {
    return p.activity.format
})

watch(() => p.activity.ID, (v) => {
    if (v) start()
})
onMounted(async () => {
    if (!p.activity.isrank) return
    // if (!p.activity.isranking) return
    // IOI赛制才展示rank
    // if (format.value === "OI") return;

    await start()
    // 进入房间
    store.state.socket.emit("activity", { activityid: p.activity.ID, com: true });
    store.state.socket.on("activity", () => {
        // if (activity.isranking) {
        console.log("socket.on activity")
        getMatchRanking()
        // }
    })
})
async function start() {
    if (p.activity.ID) {
        const data = await asyncgetactivity({ ID: p.activity.ID });
        Object.assign(activity, data);
    }
    getMatchRanking()
    selectmatchquestion()
}

const matchQuestion = ref<Studycodemodel.Imatchquestion[]>([{ score: 0 }])
async function selectmatchquestion() {
    const [data] = await asyncselectmatchquestion({ activityid: p.activity.ID })
    matchQuestion.value = data.matchquestion || []
}

const users = ref<Studycodemodel.Iuser[]>([])
const matchRanking = ref<Studycodemodel.Imatchranking[]>([])
async function getMatchRanking() {
    const { user, matchranking } = await asyncselectmatchranking({
        activityid: p.activity.ID,
        _offset: offset.value, _limit: limit.value, _order: 'df', _sortable: 'DESC'
    })
    users.value = user
    matchRanking.value = matchranking
}

// 组装数据
const tableData = computed(() => {
    const matchQ = matchQuestion.value.map(e => ({ name: e.name, type: e.type }))
    const ret = users.value.map(u => {
        let rank: { type: string, score: number }[] = []
        const { ID } = u
        // 某个人的rank Info
        const matchranking = matchRanking.value.find(e => e.userid === ID) || {}
        // [[type, df, name, ac],[...]]
        const _data = JSON.parse(matchranking?.data || '') as any[]

        rank = matchQuestion.value.map((e, i) => {
            const answered = _data.find(z => z[2] === e.name)
            // CE 分数为 null
            // [[\"代码\",null,\"消防\",\"CE\",[]],[\"代码\",null,\"彩票摇奖\",\"CE\",[]],[\"代码\",null,\"zzc 种田\",\"CE\",[]]]
            let score = answered ? (answered[1] || 0) : '-'
            if (e.type !== '代码') {
                score = answered ? '完成' : '-'
            }
            return {
                type: e.type,
                score
            }
        })
        // 是否全AC
        const resultdata = _data.map(e => e[3]).filter(e => e === 'AC').length === _data.length ? 'AC' : 'UN'
        const userquestion = {
            resultdataarr: _data.map(question => {
                const testCases = question[4] || []; // 获取测试点数组
                return testCases.map(testCase => testCase[3]); // 提取每个测试点的结果
            }),
            resultdata: _data.map(e => e[3])
        }
        // console.log(userquestion)
        return {
            rank,
            ...u,
            ...matchranking,
            resultdata,
            userquestion,
        }
    }).sort((a, b) => Number(b.df) - Number(a.df))
    return ret
})

function className(rank: { type: string, score: number }[], matchquestion: Studycodemodel.Imatchquestion, index: number) {
    const n = rank[index].score
    if (isNaN(n)) return
    const c = n / Number(matchquestion.score)
    if (c >= 0.7) {
        return 'Accepted'
    } else if (c >= 0.3) {
        return 'Unaccepted'
    } else {
        return 'CompileError'
    }
}

// 根据配置
const showScoreColumn = computed(() => {
    return activity?.show_ac_status === SHOW_AC_STATUS.SHOW_SCORE || activity?.show_ac_status === SHOW_AC_STATUS.SHOW_DETAILED_SCORE;
})
const showACColumn = computed(() => {
    return activity?.show_ac_status !== SHOW_AC_STATUS.HIDE_AC_SCORE;
});
const showDetailedScore = computed(() => {
    return activity?.show_ac_status === SHOW_AC_STATUS.SHOW_DETAILED_SCORE
})
function acgroup(data?: Array<keyof Studycodemodel.IALLTYPE>) {
    if (Array.isArray(data)) {
        const c = countBy(data, (a) => a)
        return pairs(c)
    }
    return []
}

function getResultMeta(userquestion: { resultdataarr: any[]; resultdata: any[] }, index: number) {
    const mode = activity?.show_ac_status;
    let label = '-', className = 'WT';
    // 1. 检查 userquestion 是否存在
    if (!userquestion) return { label, className };
    // 2. 检查 index 是否超出范围
    if (index === undefined || index === null || index < 0 || index >= userquestion.resultdata.length) {
        return { label, className };
    }
    // 3. 安全获取数组值
    const currentResultArr = userquestion.resultdataarr?.[index] || [];
    const currentResult = userquestion.resultdata?.[index];

    // 4. 特殊处理编译错误(CE)情况
    // if (currentResult === 'CE') {
    //     return {
    //         label: ALLTYPE['CE']?.[1] || '编译错误',
    //         className: ALLTYPE['CE']?.[1] || 'CE'
    //     };
    // }
    if (mode === SHOW_AC_STATUS.SHOW_FULL_AC) {
        // 5. 处理空数组情况
        const allAC = currentResultArr.length > 0 ? currentResultArr.every(v => v === 'AC') : false;
        className = allAC ? 'AC' : 'UN';
        label = allAC ? '通过' : '未通过';
    } else {
        // 6. 处理 resultdata 不存在的情况
        className = currentResult || 'UN';
        label = ALLTYPE[className]?.[1] || '未通过';
    }
    return {
        label,
        className: ALLTYPE[className]?.[1] || 'WT'
    };
}
</script>

<style scoped>
.rank-box {
    /* height: calc(100vh - 64px - var(--container-margin)* 5 - var(--container-header-height)); */
    margin: 0;
    --rank-header-height: 40px;
}

.rank-header {
    display: flex;
    justify-content: space-between;
    height: var(--rank-header-height);
    align-items: center;
}

.refresh {
    border-radius: 5px;
}

.rank-box {
    /* 高度计算需要重构 */
    /* height: calc(100vh - 64px - var(--container-margin)* 5 - var(--container-header-height) -40px); */
    margin: 0;
}

.match-rank-table-header-qNo,
.match-rank-table-header-qScore {
    position: relative;
}

.match-rank-table-header-qScore {
    color: #7f7f7f;
}

.tips {
    position: absolute;
    left: 0;
    /* display: inline-block; */
    /* float: left; */
}
</style>

<style>
/* #activity-common-layout .match-rank-table-header .cell {
    padding: 0;
    white-space: pre-wrap;
    line-height: normal;
} */
</style>